import hashlib
import os


def calc_big_file_md5(filepath, chunck=8192) -> str:
    """
    计算大文件MD5
    :param str filepath: 文件路径
    :param int chunck: 循环每次读取文件大小
    :return: str md5
    """
    md5 = hashlib.md5()
    file = open(filepath, 'rb')
    while 1:
        buffer = file.read(chunck)
        if not buffer:
            break
        md5.update(buffer)
    file.close()
    return md5.hexdigest()


def calc_file_md5(filepath) -> str:
    """
    计算文件MD5
    :param str filepath: 文件路径
    :return:
    """
    statinfo = os.stat(filepath)
    # 超过50MB的都算大文件
    if int(statinfo.st_size) / (1024 * 1024) >= 50:
        return calc_big_file_md5(filepath)

    file = open(filepath, 'rb')
    md5 = hashlib.md5(file.read()).hexdigest()
    file.close()
    return md5


def read_file(file: str, encoding=None) -> str:
    with open(file, 'r', encoding=encoding) as stream:
        return stream.read()
